package com.njiandan.johnson.vr360library.utils;

import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.opengl.Matrix;
import android.view.Surface;

/**
 * author：johnsonZhang on 2017/3/17 16:55
 * email：15915356@qq.com
 * 传感器
 */
public class SensorUtils {
    private static float[] mTmp = new float[16];
    private static float[] oTmp = new float[16];

    /**
     * 将传感器向量转换为矩阵
     *
     * @param event          传感器事件对象
     * @param deviceRotation 设备旋转量
     * @param output         输入输出
     */
    public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
        float[] values = event.values;
        switch (deviceRotation) {
            case Surface.ROTATION_0:
                SensorManager.getRotationMatrixFromVector(output, values);
                break;
            default:
                SensorManager.getRotationMatrixFromVector(mTmp, values);
                SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_X, SensorManager.AXIS_Y, output);
                break;
        }

        Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
    }

    /**
     * 获取传感器旋转向量
     *
     * @param event  传感器事件对象
     * @param output 输入输出
     */
    public static void getOrientation(SensorEvent event, float[] output) {
        SensorManager.getRotationMatrixFromVector(oTmp, event.values);
        SensorManager.getOrientation(oTmp, output);
    }

    /**
     * 将旋转矩阵转换为旋转向量
     *
     * @param rotationMatrix 旋转矩阵
     * @param output         输入输出
     */
    public static void getOrientationFromRotationMatrix(float[] rotationMatrix, float[] output) {
        SensorManager.getOrientation(rotationMatrix, output);
    }

}
